package sdk.webview.fmc.com.fmcsdk.util.nfc;

import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;

import java.io.IOException;
import java.nio.charset.Charset;

public class ParsedNFCRecord {
	
	//读标签数据
	public static String readTag(NdefMessage message){
		NdefRecord[] ndefrecords = message.getRecords();
		if(ndefrecords!=null){
			NdefRecord ndefrecord = ndefrecords[0];
			byte[] payload = ndefrecord.getPayload();
			return new String(payload);
		}
		return "";
	}
	
	//将对象写入标签
	public static boolean writeTag(Tag tag, NFCEntity entity){
		return writeTag(tag, entity.toString());
	}

	// 将NdefMessage对象写入标签
	public static boolean writeTag(Tag tag, String mText) {
		
		//创建NdefMessage对象和NdefRecord对象
		NdefMessage message = new NdefMessage(new NdefRecord[]{createTextRecord(mText)});
		
		int size = message.toByteArray().length;
		try {
			// 获取Ndef对象
			Ndef ndef = Ndef.get(tag);
			if (ndef != null) {
				if (!ndef.isWritable()) {
					// 只读
					return false;
				}
				if (ndef.getMaxSize() < size) {
					// 空间不足
					return false;
				}
				ndef.connect();
				// 向标签中写入数据
				ndef.writeNdefMessage(message);
				return true;
			} else {
				// 获取可以格式 化和向标签写入数据NdefFormatable对象
				NdefFormatable format = NdefFormatable.get(tag);
				// 向非NDEF格式的或未格式 化的标签写入NDEF格式数据
				if (format != null) {
					format.connect();
					format.format(message);
					// 写入成功
					return true;
				} else {
					return false;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FormatException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static NdefRecord createTextRecord(String text) {
		Charset utfEncoding = Charset.forName("UTF-8");
		byte[] textBytes = text.getBytes(utfEncoding);
		/*// 创建存储payload的字节数据
		byte[] data = new byte[textBytes.length];
		// 设置实际要写入的文本
		System.arraycopy(textBytes, 0, data, 0, textBytes.length);*/

		// 创建NdefRecord
		NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
				NdefRecord.RTD_TEXT, new byte[0], textBytes);

		return record;
	}
}
